const pool = require('../config/db')
const bcrypt = require('bcryptjs');

// 加密密码
const encryptPassword = async (plainPassword) => {
  const salt = await bcrypt.genSalt(10); // 生成盐值
  return await bcrypt.hash(plainPassword, salt); // 返回加密后的密码
};


const create = async (username, password, email) => {
  try {
    const SQL = `INSERT INTO users (username, password,email) values (?, ?, ?)`
    const newPassword = await encryptPassword(password)
    const [result] = await pool.query(SQL, [username, newPassword, email])
    console.log('用户创建成功，ID:', result.insertId);
    return result.insertId
  } catch (error) {
    console.error(error + '创建失败')
    throw error
  }
}

const userNameAll = async () => {
  const SQL = "SELECT username FROM users"
  const [rows]  = await pool.query(SQL)
  return rows
}

const findPassword = async (username) => {
  const SQL = "SELECT * FROM users WHERE username = ?"
  const [rows] = await pool.query(SQL, [username]);
  return rows[0];  // 返回密码或undefined
}

const changeUser = async(username, avatar, id) => {
  const SQL = `UPDATE users SET username = ? , avatar = ? WHERE id = ?`
  await pool.query(SQL,[username, avatar, id])
  const [user] = await pool.query('SELECT * FROM users WHERE id = ?', [id]);
  return user[0]; 
}

// 查询所有的用户
const selectUsers = async(page, size, filters = {} ) => {
  const offset = (page - 1) * size;
  let whereClause = '';
  const params = [];
    // 动态构建 WHERE 条件
  for (const [key, value] of Object.entries(filters)) {
    if (value) {
      whereClause += whereClause ? ' AND ' : ' WHERE ';
      whereClause += `${key} LIKE ?`;
      params.push(`%${value}%`);
    }
  }
  const SQL = `SELECT * FROM users ${whereClause} ORDER BY created_at Limit ? OFFSET ?`
  const [rows] = await pool.query(SQL, [ ...params, Number(size), offset])
  return rows
}

const deleteUser = (id) => {
  const SQL = 'DELETE FROM users where = ?'

  const [row] = pool.query(SQL, [id])

  return row
}
module.exports = {
  create,
  userNameAll,
  findPassword,
  changeUser,
  selectUsers,
  deleteUser
}